package com.zrkizzy.binarytree;

/**
 * 226. 翻转二叉树
 *
 * @author zhangrongkang
 * @see <a href="https://leetcode.cn/problems/invert-binary-tree/description/">https://leetcode.cn/problems/invert-binary-tree/description/</a>
 * @since 2022/11/29
 */
public class 翻转二叉树 {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode invertTree(TreeNode root) {
        dfs(root);
        return root;
    }

    private void dfs(TreeNode root) {
        // 递归到底的情况
        if (root == null) {
            return;
        }

        // 持续遍历，直到找到叶子节点
        dfs(root.left);
        dfs(root.right);

        // 交换左右子节点
        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;
    }
}
